/*
    This file is part of Emu.

    Emu is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Emu is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Emu.  If not, see <http://www.gnu.org/licenses/>. */
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QMessageBox>

#include "emacroeditor.h"

EMacroEditor::EMacroEditor(QWidget *parent, bool addmode)
    : QDialog(parent)
{
    QFormLayout *layout = new QFormLayout;
    QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok |
                                                 QDialogButtonBox::Cancel);

    _nameLine = new QLineEdit;
    _pressLine = new EMacroInEdit;
    _actionCombo = new QComboBox;
    _messageEdit = new QTextEdit;
    _statusBar = new QStatusBar;

    _messageEdit->setToolTip(
    tr("The message to send when the macro is activated."));
    _actionCombo->setToolTip(
    tr("Where to send the message."));

    _actionCombo->addItem(tr("Send to Server"));
    _actionCombo->addItem(tr("Insert into Input"));

    layout->addRow(tr("Name:"), _nameLine);
    layout->addRow(tr("Keypress:"), _pressLine);
    layout->addRow(tr("Message:"), _messageEdit);
    layout->addRow(tr("Message Action:"), _actionCombo);
    layout->addWidget(box);
    setLayout(layout);

    if (addmode)
        setWindowTitle(tr("Add Macro"));
    else
        setWindowTitle(tr("Edit Macro"));

    connect(box, SIGNAL(rejected()), this, SLOT(reject()));
    connect(box, SIGNAL(accepted()), this, SLOT(validate()));
}

void EMacroEditor::useMacro(EMacro macro)
{
    _nameLine->setText(macro.name());
    _pressLine->setPress(macro.press());
    if (macro.to() == false)
        _actionCombo->setCurrentIndex(0);
    else
        _actionCombo->setCurrentIndex(1);
    _messageEdit->setText(macro.data());
}

void EMacroEditor::validate()
{
    if (_pressLine->press() == 0) {
        QMessageBox::critical(this, tr("Error"), tr("Macro has no keypress."));
        return;
    }

    if (_messageEdit->toPlainText().isEmpty()) {
        QMessageBox::critical(this, tr("Error"),
tr("A macro without output is useless. This is probably not intended."));
        return;
    }

    _macro.setName(_nameLine->text());
    _macro.setTo(_actionCombo->currentIndex());
    _macro.setData(_messageEdit->toPlainText());
    _macro.setPress(_pressLine->press());

    accept();
}
